﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;


namespace Server
{
    public partial class Form1 : Form
    {
        private Socket server;
        private Socket client;

        private byte[] data = new byte[1024];

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //setting variable IP address & Port
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            int port;
            port = int.Parse(textBox1.Text);
            IPEndPoint localEP = new IPEndPoint(0, port);
            server.Bind(localEP);
            server.Listen(0); //increases number of backlog requests permitted

            // moved up before begin accept


            //Waiting for first client connection to be requested

            server.BeginAccept(new AsyncCallback(OnConnected), null);
            button2.Enabled = false;

            textBox2.Text = "Waiting for client .....";
        }

        //When connection is made by a client


        void OnConnected(IAsyncResult result)
        {
            try
            {
                client = server.EndAccept(result);
                textBox2.Text = "Connected to : " + client.RemoteEndPoint;
                //byte[] message = Encoding.ASCII.GetBytes("Welcome to my server"); //Message to go back to client last connected
                client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);//Parameter for Asynch Method

            }
            catch (SocketException)
            {

                CloseClient();
            }

        }
        void OnDataReceived(IAsyncResult result)
        {
            try
            {
                //Data has been received using Socket client
                int receive = client.EndReceive(result);
                if (receive == 0) //Count of characters received
                {
                    CloseClient();
                    return;
                }
                else
                {
                    string message = Encoding.ASCII.GetString(data, 0, receive);
                    //Add message received from Client to list
                    listBox1.Items.Add(message);
                    byte[] echomessage = Encoding.ASCII.GetBytes(message);
                    //Having received message will echo back using appropriate client socket object
                    client.BeginSend(echomessage, 0, echomessage.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);
                }
            }
            catch (SocketException)
            {
                CloseClient();
            }
        }

        void OnDataSent(IAsyncResult result)
        {
            try
            {
                //Data has been sent using Socket client
                int sent = client.EndSend(result); //Count of characters sent
                //Begin Async wait to receive data using existing client socket object
                client.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);

                // client.BeginReceive(dataM, 0, dataM.Length, SocketFlags.None, new AsyncCallback(OnDataSent), null);

            }
            catch (SocketException)
            {

                CloseClient();

            }


        }
        

        public void CloseClient()
        {
            //client.Close(); //close client connections
            //textBox2.Text = "Waiting for client ...";
            //server.BeginAccept(new AsyncCallback(OnConnected), null);

            client.Close();
            button2.Enabled = true;
            textBox2.Text = "Disconnected";
        }



       
    }
}



